package com.abel.redis;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisSentinelPool;

/**
 * @author heaveneleven
 * @date 2019/2/1
 */
public class LockDemo {

    public static void main(String[] args) {
        LockDemo demo = new LockDemo();
        demo.test();
        JedisPool pool = new JedisPool();

    }

    public void test(){
//        JedisSentinelPool
                JedisPool
        for(int i=0;i<20;i++){
            new Thread(new Task(String.valueOf(i+1))).start();
        }
    }

    public class Task implements Runnable{
        private String num;

        public Task(String num){
            this.num = num;
        }

        @Override
        public void run() {
            RedisLock lock = new RedisLock.Builder()
                    .ip("127.0.0.1").port(6379).build();
            try{
                if(!lock.lock("lock")){
                    return;
                }
                for(int i=0;i<5;i++){
                    System.out.println("----- "+num+" -----");
                    Thread.sleep(1);
                }
            }catch (InterruptedException e){
                //do nothing
            }finally {
                lock.unlock("lock");
            }
        }
    }
}
